package com.lzw.security.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lzw.security.common.GenericResponse;
import com.lzw.security.common.ServiceError;
import com.lzw.security.common.WeChatUrl;
import com.lzw.security.entity.User;
import com.lzw.security.ov.Status;
import com.lzw.security.ov.UserOV;
import com.lzw.security.service.WeChatService;
import com.lzw.security.util.Jcode2SessionUtil;
import com.lzw.security.util.JwtTokenUtil;
import com.lzw.security.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;

/**
 * 微信业务实现类
 */
@Service
@Slf4j
public class WeChatServiceImpl implements WeChatService {

    @Value("${weChat.appid}")
    private String appid;

    @Value("${weChat.secret}")
    private String secret;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public UserOV wxLogin(String code) throws Exception{
        UserOV<String> userOV = new UserOV<>();
        System.out.println("code:"+code);
        JSONObject sessionInfo = JSONObject.parseObject(jcode2Session(code));
        //这里如果是空的 报错
        Assert.notNull(sessionInfo,"code 无效");
//        Assert.isTrue(null == sessionInfo.getInteger("errcode"),sessionInfo.getString("errmsg"));
        String openid = (String) sessionInfo.get("openid");//openid同一用户同一应用唯一，unionid同一用户不同应用唯一。
        sessionInfo.get("session_key");
        // 获取用户唯一标识符 openid成功 向security发起一个请求
        // 模拟从数据库获取用户信息
        if(openid==null){
            userOV.getMeta().setStatus(200).setMessage("这个code获取不到openId");
            return userOV;
        }
        System.out.println("openid"+openid);
        HttpPost httpPost = new HttpPost("http://localhost:4268/mylogin");
        List<NameValuePair> params=new ArrayList<NameValuePair>();
        //建立一个NameValuePair数组，用于存储欲传送的参数
        params.add(new BasicNameValuePair("username",openid));
        params.add(new BasicNameValuePair("password","546100"));
        //设置编码
        httpPost.setEntity(new UrlEncodedFormEntity(params));//添加参数
        String result = EntityUtils.toString(new DefaultHttpClient().execute(httpPost).getEntity());
        JSONObject resultJson = JSONObject.parseObject(result);
//        String login = Jcode2SessionUtil.login(openid);
//        System.out.println(login);
        System.out.println(resultJson);
        userOV.getMeta().setStatus(200);
        userOV.setData((String) resultJson.get("data"));
        return userOV;
    }

    /**
     * 登录凭证校验
     * @param code
     * @return
     * @throws Exception
     */
    private String jcode2Session(String code)throws Exception{
        String sessionInfo = Jcode2SessionUtil.jscode2session(appid,secret,code,"authorization_code");//登录grantType固定
        return sessionInfo;
    }
}
